package com.cgbl.cg.ui.mine

import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.cgbl.cg.BR
import com.cgbl.cg.R
import com.cgbl.cg.adapter.CouponAdapter
import com.cgbl.cg.adapter.WorksAdapter
import com.cgbl.cg.databinding.AppActivityPersonalCouponBinding
import com.cgbl.cg.vm.mine.PersonalCouponViewModel
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.model.CouponBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

@Route(path = AppConstants.Router.Mine.A_MINE_PERSONAL_COUPON)
class PersonalCouponActivity :
    GLBaseActivity<AppActivityPersonalCouponBinding, PersonalCouponViewModel>() {

    lateinit var couponAdapter: CouponAdapter

    override fun initComponents() {
        initTiterBar()
        initView()
        viewModel.refresh()
    }

    private fun initTiterBar() {
        val titleView = findViewById<TextView>(R.id.tv_title)
        val backView = findViewById<ImageView>(R.id.iv_back)
        titleView.text = "优惠券"
        backView.setOnClickListener { finish() }
    }

    override fun initViewObservable() {
        viewModel.uc.changeTabEvent.observe(this) {
            couponAdapter.setType(it)
        }
        viewModel.uc.refreshCouponEvent.observe(this) {
            if (it.isEmpty()) {
                val emptyView = layoutInflater.inflate(R.layout.app_layout_empty, null)
                couponAdapter.setEmptyView(emptyView)
            }
            couponAdapter.setNewInstance(it as MutableList<CouponBean>?)
            binding.refreshLayout.finishLoadMore()
            binding.refreshLayout.finishRefresh()
        }
        viewModel.uc.loadMoreCouponEvent.observe(this) {
            couponAdapter.addData(it)
            binding.refreshLayout.finishLoadMore()
            binding.refreshLayout.finishRefresh()
        }
    }

    private fun initView() {
        couponAdapter = CouponAdapter()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@PersonalCouponActivity)
            adapter = couponAdapter
        }
        binding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                viewModel.refresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                viewModel.loadMore()
            }
        })
    }

    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_activity_personal_coupon

    override fun initVariableId(): Int = BR.viewModel
}